/**
 * 2018年5月6日下午7:29:17
 */
package com.an.nopro.app.framework.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**

 * @目的：系统用户implements UserDetails,即为Spring security的用户.<br>
 * 
 * @author 86171
 * @date 2018年5月6日下午7:29:17
 * 
 */
@Entity
//@Table(name="SYS_USER")
public class SysUser implements UserDetails {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1137690716088905223L;

	/**
	 * 用户ID
	 */
	@Id
	@GeneratedValue
	private Long id;
	/**
	 * 用户姓名
	 */
	private String username;
	/**
	 * 密码
	 */
	private String password;
	
	/**
	 * 用户角色，属于多对多的关系。
	 */
	@ManyToMany(cascade= {CascadeType.REFRESH},fetch=FetchType.EAGER)
	private List<SysRole> roles;
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> auths = new ArrayList<>();
		List<SysRole> roles = this.getRoles();
		for (SysRole sysRole : roles) {
			auths.add(new SimpleGrantedAuthority(sysRole.getName()));
		}
		return auths;
	}

	public List<SysRole> getRoles() {
		return roles;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}


	public void setUserName(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRoles(List<SysRole> roles) {
		this.roles = roles;
	}

	@Override
	public String getPassword() {
		return this.password;
	}
	
	@Override
	public String getUsername() {
		return this.username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public String toString() {
		return "SysUser [id=" + id + ", username=" + username + ", password=" + password + ", roles=" + roles + "]";
	}

}
